//
//  PhotoWallController.m
//  ox
//
//  Created by 喻杰 on 2016/10/26.
//  Copyright © 2016年 fengge. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "PhotoWallController.h"


#define waterfallCell @"waterfallCell"
#define waterfallheader @"waterfallHeader"

#define getPhoto @"select * from ox_record order by r_id desc limit ?,?"
#define getPhotoWithPoiName @"select * from ox_record where poi_name=? order by r_id desc limit ?,?"

@interface PhotoWallController ()

@end

@implementation PhotoWallController

@synthesize waterfallLayout,arr,collection,header,page,size,isEnd,poiName,lat,lon;



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.view.backgroundColor  = [UIColor whiteColor];
    
    //选择拍照或者图片
    UIBarButtonItem* takePhoto =  [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemCamera target:self action:@selector(showTakePicture:)];
    self.navigationItem.rightBarButtonItem =takePhoto;
    
    [self firstLoadData];
    
    //加载瀑布流
    waterfallLayout =[[CHTCollectionViewWaterfallLayout alloc] init];
    waterfallLayout.sectionInset = UIEdgeInsetsMake(0, 5, 5, 5);
    waterfallLayout.headerHeight = 10;
    waterfallLayout.footerHeight = 0;
    waterfallLayout.minimumColumnSpacing = 5;
    waterfallLayout.minimumInteritemSpacing = 5;
    
    //初始化collectionview
    collection = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:waterfallLayout];
    collection.dataSource =self;
    collection.delegate =self;
    collection.backgroundColor = [[UIColor alloc]initWithRed:245.0/255.0 green:245.0/255.0 blue:245.0/255.0 alpha:1];
    
    //使用mjrefresh 下拉刷新
    collection.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(reloadMyData)];
    collection.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(appendData)];
    
    //注册 瀑布流单元格类
    [collection registerClass:[CHTCollectionViewWaterfallCell class]forCellWithReuseIdentifier:waterfallCell];
    [self.view addSubview:collection];
    
    if(arr.count < 10){
        [collection.mj_footer setHidden:YES];
    }
}


-(void)firstLoadData{
    page = 0;
    size = 10;
    isEnd =false;
    DBHelper* helper = [[DBHelper alloc]init];
    if(poiName){
        arr = [helper listBy:getPhotoWithPoiName params:@[poiName,@(page*size),@((page+1)*size)]];
    }else{
        arr = [helper listBy:getPhoto params:@[@(page*size),@((page+1)*size)]];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



-(void) showTakePicture:(UIBarButtonItem*)sender{
    self.definesPresentationContext =YES;
    ChooseImagePickSourceTypeController * choose =[[ChooseImagePickSourceTypeController alloc]init ];
    choose.modalPresentationStyle = UIModalPresentationCustom;
    choose.showPickView = ^(UIButton * sender){
        UIImagePickerController* pick =[[UIImagePickerController alloc]init];
        if(sender.tag == 1){
            pick.sourceType =UIImagePickerControllerSourceTypeCamera;
        }else{
            pick.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        }
        pick.delegate = self;
        [self presentViewController:pick animated:YES completion:nil];
    };
    [self presentViewController:choose animated:NO completion:nil];
}


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary<NSString *,id> *)editingInfo {
}

//选择或者拍摄图片结束
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    [picker dismissViewControllerAnimated:YES completion:nil];
    //将图片调整朝上
    UIImage * image = info[UIImagePickerControllerOriginalImage];
    if (image.imageOrientation != UIImageOrientationUp){
        UIGraphicsBeginImageContextWithOptions(image.size, NO, image.scale);
        [image drawInRect:(CGRect){0, 0, image.size}];
        image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }
    SharePhotoController * sharePhoto =[[SharePhotoController alloc]init];
    [sharePhoto setImage:image];
    if(picker.sourceType ==UIImagePickerControllerSourceTypeCamera){
        UIImageWriteToSavedPhotosAlbum(image,nil, nil, nil);//保存到相簿
    }
    UINavigationController* nav =[[UINavigationController alloc]initWithRootViewController:sharePhoto];
    [self presentViewController:nav animated:YES completion:nil];
}


- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil ];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return arr.count;
}

// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    CHTCollectionViewWaterfallCell * cell =  (CHTCollectionViewWaterfallCell*)[collectionView dequeueReusableCellWithReuseIdentifier:waterfallCell forIndexPath:indexPath];
    NSError * err;
    OxRecordModel * record =[[OxRecordModel alloc]initWithDictionary:arr[indexPath.row] error:&err];
    if(err){
        DDLogError(@"%@",err);
        return nil;
    }
    [self loadCellView:cell data:record];
    return cell;
}



- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat width = (self.view.frame.size.width-50)/2;
    NSError * err;
    OxRecordModel * record =[[OxRecordModel alloc]initWithDictionary:arr[indexPath.row] error:&err];
    CGFloat height;
    if(err){
        DDLogError(@"%@",err);
        height = self.view.frame.size.height * width /self.view.frame.size.width;
    }else{
        height = record.imageHeight * width /record.imageWidth;
    }
    return CGSizeMake(width, height+50);
}


- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    ImageVC * vc = [[ImageVC alloc] init];
    NSString* fileName = [arr[indexPath.row] objectForKey:@"image_url"];
    NSURL* url = [NSURL fileURLWithPath:fileName];
    [vc setUrl:url];
    [self.navigationController pushViewController:vc animated:YES];
}


-(void) reloadMyData{
    DDLogInfo(@"reload");
    DBHelper* helper = [[DBHelper alloc]init];
    page = 0;
    isEnd =false;
    [collection.mj_footer setHidden:NO];
    if(poiName){
        arr =[helper listBy:getPhotoWithPoiName params:@[poiName,@(page*size),@((page+1)*size)]];
    }else{
        arr = [helper listBy:getPhoto params:@[@(page*size),@((page+1)*size)]];
    }
    if(arr.count < size){
        [collection.mj_footer setHidden:YES];
    }
    [collection.mj_header endRefreshing];
    [collection reloadData];
    
}

-(void) appendData{
    DDLogInfo(@"appendData");
    [collection.mj_footer beginRefreshing];
    DBHelper* helper =  [[DBHelper alloc]init];
    if(!isEnd)
        page++;
    NSMutableArray<NSMutableDictionary*>* array;
    if(poiName){
        array =[helper listBy:getPhotoWithPoiName params:@[poiName,@(page*size),@((page+1)*size)]];
    }else{
        array = [helper listBy:getPhoto params:@[@(page*size),@((page+1)*size)]];
    }
    if(array.count<size){
        isEnd =true;
        [collection.mj_footer setHidden: YES];
    }
    [arr addObjectsFromArray:array];
    [collection.mj_footer endRefreshing];
    [collection reloadData];
}

-(void) loadCellView:(CHTCollectionViewWaterfallCell*)cell data:(OxRecordModel*) record{
    [cell.imageView sd_setImageWithURL:[NSURL fileURLWithPath:record.imageUrl]];
    
    cell.title.text = [NSString stringWithFormat:@"%@xue:",record.recorder];
    cell.content.text = record.content;
    
    [cell.imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(cell.contentView).with.insets(UIEdgeInsetsMake(3, 3, 48, 3));
    }];
    [cell.content mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(cell.contentView).offset(23);
        make.bottom.mas_equalTo(cell.contentView).offset(-3);
        make.right.mas_equalTo(cell.contentView).offset(3);
        make.height.mas_equalTo(20);
    }];
    [cell.title mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(cell.contentView).offset(3);
        make.bottom.mas_equalTo(cell.content).offset(-23);
        make.right.mas_equalTo(cell.contentView).offset(3);
        make.height.mas_equalTo(20);
    }];
}


//-(void)viewWillAppear:(BOOL)animated{
//    collection.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放
//}
//
//-(void)viewWillDisappear:(BOOL)animated{
//    collection.delegate = nil; // 不用时，置nil
//}


@end
